<template>
    <view>
        <view v-if="readOnly" class="rx-disabled">{{getAddressStr}}</view>
        <view v-else>
            <view class="MAddress">
                <view class="MAddress-center">
                    <picker :disabled="readOnly" style="width: 100%" mode="selector" :value="province" rangeKey="AREA_NAME_" @change="setProvince" :range="provinces">
                        <view :class="[selectedAddress.province?'uni-input':'uni-input-name']">
                            <span class="uni-input-span">{{selectedAddress.province?selectedAddress.province:i18n('province','省')}}</span>
                            <my-icon style="color: rgba(201, 201, 201, 1)" type="icon-jiantou_liebiaozhankai"></my-icon>
                        </view>
                    </picker>
                </view>
                <view class="MAddress-center" v-if="showCity">
                    <picker :disabled="readOnly" style="width: 100%" mode="selector" :value="city" rangeKey="AREA_NAME_" @change="setCity" :range="cities">
                        <view :class="[selectedAddress.city?'uni-input':'uni-input-name']">
                            <span class="uni-input-span">{{selectedAddress.city?selectedAddress.city:i18n('city','市')}}</span>
                            <my-icon style="color: rgba(201, 201, 201, 1)" type="icon-jiantou_liebiaozhankai"></my-icon>
                        </view>
                    </picker>
                </view>
                <view class="MAddress-center" v-if="showCounty">
                    <picker :disabled="readOnly" style="width: 100%" mode="selector" :value="county" rangeKey="AREA_NAME_" @change="setCounty" :range="counties">
                        <view :class="[selectedAddress.county?'uni-input':'uni-input-name']">
                            <span class="uni-input-span">{{selectedAddress.county?selectedAddress.county:i18n('county','县(区)')}}</span>
                            <my-icon style="color: rgba(201, 201, 201, 1)" type="icon-jiantou_liebiaozhankai"></my-icon>
                        </view>
                    </picker>
                </view>
            </view>
            <uv-textarea :disabled="readOnly" style="margin-top: 0.5rem;" :maxlength="300" v-if="showAddress" v-model="address" :placeholder="i18n('address','请输入详情地址')" @change="setAddress"></uv-textarea>
        </view>
    </view>
</template>

<script>
import MForm from "../js/MForm";
import {FormApi} from "@/api/FormApi.js";
import Util from '@/js/Util.js'
export default {
    name: "MAddress",
    mixins:[MForm],
    data() {
        return {
            curValue:[],
            province: "",
            //省
            provinces: [],
            city: "",
            //市
            cities: [],
            county: "",
            //县、区
            counties: [],
            //详细地址
            address: "",
            //province,province_code,city,city_code,county,county_code,address
            selectedAddress: {},
            addressRuleState:{
                'province':{
                    state:true,
                    msg:this.i18n('provinceRequired','省必填！')
                },
                'city':{
                    state:true,
                    msg:this.i18n('cityRequired','市必填！')
                },
                'county':{
                    state:true,
                    msg:this.i18n('countyRequired','县/区必填！')
                },
                'address':{
                    state:true,
                    msg:this.i18n('addressRequired','详细地址必填！')
                }
            }
        }
    },
    computed:{
        getAddressStr(){
            let str="";
            if (this.selectedAddress.province) {
                str += this.selectedAddress.province;
            }
            if (this.selectedAddress.city) {
                str +=this.selectedAddress.city;
            }
            if (this.selectedAddress.county) {
                str +=this.selectedAddress.county;
            }
            if (this.selectedAddress.address) {
                str +=this.selectedAddress.address;
            }
            return str;
        },
        showCity(){
            return this.metadata.options.isCity;
        },
        showCounty(){
            return this.metadata.options.isCounty ;
        },
        showAddress(){
            return this.metadata.options.isAddress;
        },
    },
    created() {
        this.initSelectedAddress();
        this.initValue(this.value);
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"componentsLang",key);
        },
        initSelectedAddress(){
            this.selectedAddress = {
                province: "",
                province_code: ""
            };
            if(this.showCity){
                this.selectedAddress['city'] = '' ;
                this.selectedAddress['city_code'] = '' ;
            }
            if(this.showCounty){
                this.selectedAddress['county'] = '' ;
                this.selectedAddress['county_code'] = '' ;
            }
            if(this.showAddress){
                this.selectedAddress['address'] = '' ;
            }
        },
        initValue(val) {
            if (!val){
                //先加载省份数据
                if (!this.readOnly) {
                    this.getsProvince("provinces",  {});
                }
                return;
            }
            this.selectedAddress = JSON.parse(val);
            this.getsProvince("provinces",  {},function (self){
                if (self.selectedAddress.province_code) {
                    if (self.selectedAddress.province_code != "") {
                        self.province = self.getCurIndex(self.selectedAddress.province_code,self.provinces);
                        let param = {};
                        param["PARENT_CODE_"] = self.selectedAddress.province_code;
                        if(self.showCity){
                            self.getsProvince("cities", param,function (self){
                                if (self.selectedAddress.city_code != "") {
                                    self.city = self.getCurIndex(self.selectedAddress.city_code,self.cities);
                                    let param = {};
                                    param["PARENT_CODE_"] = self.selectedAddress.city_code;
                                    if(self.showCounty){
                                        self.getsProvince("counties", param,function (){
                                            if (self.selectedAddress.county_code != "") {
                                                self.county = self.getCurIndex(self.selectedAddress.county_code,self.counties);
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                }
            })
            this.address = this.selectedAddress.address;
        },
        async getsProvince(key, config,callback) {
            let _self = this ;
            if(this[key] && this[key].length>0  ){
                if(callback){
                    callback(_self)
                }
                return;
            }
            FormApi.queryAddress(key, config).then(res => {
                if (!res.success) return;
                if (key == "provinces") {
                    _self.provinces = res.data;
                } else if (key == "cities") {
                    _self.cities = res.data;
                } else {
                    _self.counties = res.data;
                }
                if(callback){
                    callback(_self)
                }
            })
        },
        //获取下标
        getCurIndex(code,ary){
            let index = "";
            for (let i = 0; i < ary.length; i++) {
                if (code == ary[i].AREA_CODE_) {
                    index=i;
                    break;
                }
            }
            return index;
        },
        setProvince(e) {
            const {
                provinces
            } = this;
            //当前选择的下标
            let index = e.detail.value;
            let value =provinces[index].AREA_NAME_;
            if (value) {
                this.selectedAddress.province = value;
                for (let i = 0; i < provinces.length; i++) {
                    if (value == provinces[i].AREA_NAME_) {
                        this.selectedAddress.province_code = provinces[i].AREA_CODE_;
                        break;
                    }
                }
                if (this.showCity) {
                    this.cities = [];
                    this.counties = [];
                    this.city = "";
                    this.county = "";
                    this.selectedAddress.city = "";
                    this.selectedAddress.city_code = "";
                    if (this.showCounty) {
                        this.selectedAddress.county = "";
                        this.selectedAddress.county_code = "";
                    }
                }
            } else {
                this.selectedAddress.province = "";
                this.selectedAddress.province_code = "";
                if (this.showCity) {
                    this.city = "";
                    this.setCity();
                    this.cities = [];
                    if (this.showCounty) {
                        this.county = "";
                        this.setCounty();
                        this.counties = [];
                    }
                }
            }
            this.updateAddress()
        },
        setCity(e) {
            const {
                cities
            } = this;
            //当前选择的下标
            let index = e.detail.value;
            let value =cities[index].AREA_NAME_;
            if (value) {
                this.selectedAddress.city = value;
                for (let i = 0; i < cities.length; i++) {
                    if (value == cities[i].AREA_NAME_) {
                        this.selectedAddress["city_code"]=cities[i].AREA_CODE_;
                        break;
                    }
                }
                if (this.showCounty) {
                    this.county = "";
                    this.counties = [];
                    this.selectedAddress.county = "";
                    this.selectedAddress.county_code = "";
                }
            } else {
                this.selectedAddress.city = "";
                this.selectedAddress.city_code = "";
                this.county = "";
                if (this.showCounty) {
                    this.setCounty();
                    this.counties = [];
                }
            }
            this.updateAddress()
        },
        setCounty(e) {
            const { counties } = this;
            //当前选择的下标
            let index = e.detail.value;
            let value =counties[index].AREA_NAME_;
            if (value) {
                this.selectedAddress.county = value;
                for (let i = 0; i < counties.length; i++) {
                    if (value == counties[i].AREA_NAME_) {
                        this.selectedAddress.county_code = counties[i].AREA_CODE_;
                        break;
                    }
                }
            } else {
                this.county = "";
                this.selectedAddress.county = "";
                this.selectedAddress.county_code = "";
            }
            this.updateAddress()
        },
        setAddress() {
            this.selectedAddress.address = this.address;
            this.updateAddress()
        },
        updateAddress:Util.debounce(function () {
            let value = JSON.stringify(this.selectedAddress);
            this.setData(value);
        }, 300),
    },
    watch: {
        value(val) {
            this.initValue(val);
        }
    },
}
</script>

<style scoped>
.rx-disabled{
    background: rgba(245, 246, 249, 1);
    display: flex;
    align-items: center;
    padding: 0.5rem;
    border-radius: 4px;
    border: none;
    margin-top: 0.5rem;
    min-height: 1rem;
}
.MAddress{
    width: 100%;
    display: flex;
    grid-gap: 0.5rem;
    overflow: hidden;
    flex-wrap: wrap;
}
.MAddress-center{
    flex: 1;
    height: 2rem;
    border-radius: 0.17rem;
    display: flex;
    align-items: center;
    border: 1px solid rgba(232, 232, 232, 1);
    padding: 0rem 0.5rem;

}
.uni-input{
    flex: 1;
    color: rgba(0, 0, 0, 0.85);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: flex;
    align-items: center;
}
.uni-input-name{
    flex: 1;
    color: rgba(0, 0, 0, 0.45);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: flex;
    align-items: center;
}
.uni-input-span{
    flex: 1;
    margin-right: 0.5rem;
}
</style>
